#include "../DWMRICore/DTI.h"
#include "../DWMRICore/Scalar.h"

#include <teem/ten.h>

#include <omp.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>

char *dti_pathname = NULL;
char *mask_pathname = NULL;
char *dst_pathname = NULL;

CDTI *pDTI = NULL;
CScalar *pMASK = NULL;

/* MLS fiber tracking parameters */
float MLSSize = 2.0f;
CPoint3F *pSamplePoints = NULL;
float *pSamplePointsWeight = NULL;

int scale = 4;

void PrintUsage()
{
	printf("Usage: ComputeCL -dti dti_file -mask mask_file -dst dst_file\n");
}

int ParseArguments(const int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-dti") == 0) {
			dti_pathname = argv[++i];
		} else if (strcmp(argv[i], "-dst") == 0) {
			dst_pathname = argv[++i];
		} else if (strcmp(argv[i], "-mask") == 0) {
			mask_pathname = argv[++i];
		} else {
			return -1;
		}
	}

	if (dti_pathname == NULL || mask_pathname == NULL || dst_pathname == NULL)
		return -2;

	return 0;
}

void CreateMLSSamplePoints()
{
	SafeDeleteArray(pSamplePoints);
	SafeDeleteArray(pSamplePointsWeight);
	pSamplePoints = new CPoint3F[SAMPLE_POINT_NUM];
	pSamplePointsWeight = new float[SAMPLE_POINT_NUM];

	pSamplePoints[0].m_x = 0.0f;
	pSamplePoints[0].m_y = 0.0f;
	pSamplePoints[0].m_z = 0.0f;
	pSamplePointsWeight[0] = 1.0f;

	clock_t seed = clock();
	srand(seed);

	for (int i = 1; i < SAMPLE_POINT_NUM; ++i) {
		bool flag = false;
		CPoint3F pt;
		while(!flag) {
			float a = (float)rand() / (float)RAND_MAX * 2.0f * (float)M_PI;
			float b = (float)rand() / (float)RAND_MAX * (float)M_PI;
			float r = (float)rand() / (float)RAND_MAX;

			pt.m_x = r * sinf(a) * sinf(b);
			pt.m_y = r * sinf(a) * cosf(b);
			pt.m_z = r * cosf(a);

			flag = true;
			for (int j = 0; j < i; ++j) {
				float dis = Distance(pSamplePoints[j], pt);
				if (dis < 0.3f) {
					flag = false;
					break;
				}
			}
		}

		pSamplePoints[i] = pt;
		pSamplePointsWeight[i] = InnerProduct(pSamplePoints[i], pSamplePoints[i]) * 4.0f;
		pSamplePointsWeight[i] = expf(pSamplePointsWeight[i] / -2.5f);
	}
}

void DTIMLSFilter(const CPoint3F pos, float *lastDTI, float *filteredDTI)
{
	float m[9];
	TEN_T2M(m, lastDTI);

	CPoint3F samples[SAMPLE_POINT_NUM];
	float length[SAMPLE_POINT_NUM];
	float max_length = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = pSamplePoints[i].m_x * m[0] + pSamplePoints[i].m_y * m[1] + pSamplePoints[i].m_z * m[2];
		samples[i].m_y = pSamplePoints[i].m_x * m[3] + pSamplePoints[i].m_y * m[4] + pSamplePoints[i].m_z * m[5];
		samples[i].m_z = pSamplePoints[i].m_x * m[6] + pSamplePoints[i].m_y * m[7] + pSamplePoints[i].m_z * m[8];
		length[i] = sqrtf(InnerProduct(samples[i], samples[i]));
		if (length[i] > max_length)
			max_length = length[i];
	}

	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = samples[i].m_x / max_length * MLSSize + pos.m_x;
		samples[i].m_y = samples[i].m_y / max_length * MLSSize + pos.m_y;
		samples[i].m_z = samples[i].m_z / max_length * MLSSize + pos.m_z;
	}

	memset(filteredDTI, 0, sizeof(float)*7);
	float temp_DTI[7];
	float weight = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		if (pMASK->GetScalar(samples[i]) < 0.5f) {
			continue;
		}
		pDTI->GetDTI(samples[i], temp_DTI);

		for (uint j = 0; j < 7; ++j) {
			filteredDTI[j] += pSamplePointsWeight[i] * temp_DTI[j];
		}
		weight += pSamplePointsWeight[i];
	}

	for (uint j = 0; j < 7; ++j) {
		filteredDTI[j] = filteredDTI[j] / weight;
	}
}

void ComputeCL(CScalar *cl)
{
	int w = pDTI->GetWidth() * scale;
	int h = pDTI->GetHeight() * scale;
	int d = pDTI->GetDepth() * scale;

	omp_set_num_threads(64);
#pragma omp parallel for  
	for (int z = 0; z < d; ++z) {
		for (int y = 0; y < h; ++y) {
			for (int x = 0; x < w; ++x) {
				float *initDTI = new float[7];
				float *filteredDTI = new float[7];

				float cx = (float)x / (float)scale;
				float cy = (float)y / (float)scale;
				float cz = (float)z / (float)scale;
				
				CPoint3F pos = CPoint3F(cx, cy, cz);
				
				pDTI->GetDTI(pos, initDTI);
				DTIMLSFilter(pos, initDTI, filteredDTI);

				if (pMASK->GetScalar(pos) > 0.5f) {
					float temp = pDTI->DTI2FA(filteredDTI);
					cl->SetScalar(x ,y, z, temp);
				} else {
					cl->SetScalar(x, y, z, 0.0f);
				}

				SafeDeleteArray(initDTI);
				SafeDeleteArray(filteredDTI);
			}
		}

	}
}

int main(int argc, char *argv[])
{
	if (ParseArguments(argc, argv) != 0) {
		PrintUsage();
		return 0;
	}

	pDTI = new CDTI();
	pDTI->OpenDTIFile(dti_pathname);
	pMASK = new CScalar();
	pMASK->OpenScalarFile(mask_pathname);

	uint w = pDTI->GetWidth();
	uint h = pDTI->GetHeight();
	uint d = pDTI->GetDepth();

	CScalar *res = new CScalar();
	res->CreateScalar(w*scale, h*scale, d*scale);

	CreateMLSSamplePoints();

	ComputeCL(res);

	res->SaveScalarFile(dst_pathname);

	SafeDelete(pDTI);
	SafeDelete(pMASK);
	SafeDelete(res);

	return 0;
}